package com.huxiu.yd;

import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.huxiu.yd.net.GsonRequest;
import com.huxiu.yd.net.NetworkConstants;
import com.huxiu.yd.net.NetworkHelper;
import com.huxiu.yd.net.model.ChatMessage;
import com.huxiu.yd.net.responses.BaseResponse;
import com.huxiu.yd.net.responses.ChatMessageListResponse;
import com.huxiu.yd.utils.Constants;
import com.huxiu.yd.utils.ErrorResponseException;
import com.huxiu.yd.utils.Global;
import com.huxiu.yd.utils.ImageUtils;
import com.huxiu.yd.utils.Utils;
import com.huxiu.yd.view.CheckKeyboardLinearLayout;
import com.makeramen.roundedimageview.RoundedImageView;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;

public class ChatActivity extends BaseActivity implements AdapterView.OnItemLongClickListener, PullToRefreshBase.OnRefreshListener2<ListView>, CheckKeyboardLinearLayout.OnKeyboardShownListener {

    public static final String EXTRA_UID = "uid";
    public static final String EXTRA_NAME = "name";
    public static final String EXTRA_AVATAR = "avatar";

    private static final int DEFAULT_TIME_SPAN = 300;  //5 minutes;

    @InjectView(R.id.back)
    ImageView back;

    @InjectView(R.id.title)
    TextView title;

    @InjectView(R.id.list)
    PullToRefreshListView list;

    @InjectView(R.id.send_button)
    TextView sendButton;

    @InjectView(R.id.empty)
    TextView emptyView;

    @InjectView(R.id.msg_edit)
    EditText msgEdit;

    @InjectView(R.id.whole_view)
    CheckKeyboardLinearLayout wholeView;

    private String ta_uid, ta_name, ta_avatar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        ButterKnife.inject(this);
        ta_uid = getIntent().getStringExtra(EXTRA_UID);
        if (TextUtils.isEmpty(ta_uid)) {
            Toast.makeText(this, R.string.chat_without_uid, Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        ta_name = getIntent().getStringExtra(EXTRA_NAME);
        ta_avatar = getIntent().getStringExtra(EXTRA_AVATAR);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        if (TextUtils.isEmpty(ta_name)) {
            title.setText(R.string.private_msg);
        } else {
            title.setText(ta_name);
        }

        adapter = new MyMessageAdapter();
        list.setAdapter(adapter);
        list.setOnRefreshListener(this);
        list.setEmptyView(emptyView);
        list.setState(PullToRefreshBase.State.INIT_REFRESHING, true);
        list.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == SCROLL_STATE_TOUCH_SCROLL) {
                    Utils.closeKeyboard(msgEdit);
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });
        wholeView.setListener(this);

        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(msgEdit.getText().toString())) {
                    sendMsg();
                }
            }
        });
    }

    private void sendMsg() {
        Map<String, String> params = new LinkedHashMap<>();
        params.put("act", "send_message");
        params.put("to_uid", ta_uid);
        params.put("content", msgEdit.getText().toString());
        String url = NetworkConstants.MEMBER_URL;
        GsonRequest<BaseResponse> request = new GsonRequest<>(url, Request.Method.POST, BaseResponse.class,
                true, params, new Response.Listener<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse response) {
                dismissProgress();
                if (response.isSuccess()) {
                    getItems(0);
                    msgEdit.setText("");
                } else {
                    Utils.showToast(response.msg);
                }
            }
        }, mErrorListener);
        mQueue.add(request);
//        mQueue.start();
        showProgress();
    }

    protected Response.ErrorListener mErrorListener = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            refreshComplete();
            dismissProgress();
            Throwable t = error.getCause();
            if (t instanceof ErrorResponseException) {
                Utils.showToast(error.getMessage());
            } else {
                Utils.showToast(R.string.generic_failure);
            }
        }
    };

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        return false;
    }

    private int currentPage = 0;

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        getItems(1);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        getItems(currentPage + 1);
    }

    private List<ChatMessage> items = new ArrayList<>();

    MyMessageAdapter adapter;

    private void getItems(final int page) {
        String url = NetworkConstants.MEMBER_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("page", Integer.toString(page));
        params.put("act", "get_dialogue_list");
        params.put("other_user_id", ta_uid);
        GsonRequest<ChatMessageListResponse> request = new GsonRequest<>(url, Request.Method.POST,
                ChatMessageListResponse.class, true, params,
                new Response.Listener<ChatMessageListResponse>() {
                    @Override
                    public void onResponse(ChatMessageListResponse response) {
                        if (response.isSuccess()) {
                            if (page <= 1) {
                                items.clear();
                            }
                            Collections.addAll(items, response.data);
                            adapter.notifyDataSetChanged();
                            scrollToBottom();
                            currentPage = response.page;
//                            if (response.page >= response.max_page) {
//                                list.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
//                            }
                        } else {
                            Utils.showToast(response.msg);
                        }

                        refreshComplete();
//                        emptyView.setText("您还没有收到任何私信哦~");
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Utils.showErrorMsg(error);
                refreshComplete();
            }
        });
        NetworkHelper.getInstance().addToRequestQueue(request);
//        NetworkHelper.getInstance().getRequestQueue().start();
    }

    private void refreshComplete() {
        list.postDelayed(new Runnable() {
            @Override
            public void run() {
                list.onRefreshComplete();
            }
        }, 100);
    }

    private void scrollToBottom() {
        ListView refreshableView = list.getRefreshableView();
        refreshableView.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_CANCEL, 0, 0, 0));
        Utils.scrollListView(refreshableView, refreshableView.getCount() - 1, 100);
    }

    @Override
    public void onKeyboardShown() {
        scrollToBottom();
    }

    @Override
    public void onKeyboardHidden() {

    }

    private class MyMessageAdapter extends BaseAdapter {

        Date today, yesterday, year;

        public MyMessageAdapter() {
            super();
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            today = calendar.getTime();
            calendar.add(Calendar.DATE, -1);
            yesterday = calendar.getTime();
            calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            calendar.set(Calendar.DAY_OF_YEAR, 1);
            year = calendar.getTime();
        }

        @Override
        public int getCount() {
            return items.size();
        }

        @Override
        public ChatMessage getItem(int position) {
            return items.get(position);
        }

        @Override
        public long getItemId(int position) {

            ChatMessage msg = getItem(position);
            long id = 0;
            try {
                id = Long.parseLong(msg.id);
            } catch (Exception e) {
            }
            return id;
        }

        @Override
        public int getItemViewType(int position) {
            ChatMessage msg = getItem(position);
            return msg.message_type;
        }

        @Override
        public int getViewTypeCount() {
            return 2;
        }

        View.OnClickListener clickTaListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ChatActivity.this, UserProfileActivity.class);
                intent.putExtra(Constants.USER_ID_KEY, ta_uid);
                intent.putExtra("avatar", ta_avatar);
                intent.putExtra("username", ta_avatar);
                startActivity(intent);
            }
        };

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            ViewHolder vh;
            ChatMessage msg = getItem(position);
            if (view == null) {
                view = getLayoutInflater().inflate(msg.message_type == 0 ? R.layout.conversation_to_me : R.layout.conversation_from_me,
                        parent, false);
                vh = new ViewHolder(view);
                view.setTag(vh);
            }
            vh = (ViewHolder) view.getTag();
            String avatar;
            if (msg.message_type == 0)
                avatar = ta_avatar;
            else
                avatar = Global.user.avatar;
            ImageLoader.getInstance()
                    .displayImage(avatar, vh.avatar,
                            ImageUtils.getAvatarDisplayOption());
            if (msg.message_type == 0) {
                vh.avatar.setOnClickListener(clickTaListener);
            } else {

            }
            if (!displayTime(position)) {
                vh.time.setVisibility(View.GONE);
            } else {
                vh.time.setVisibility(View.VISIBLE);
                long time = msg.create_time * 1000;
                if (Utils.isInSameMinute(time, System.currentTimeMillis())) {
                    vh.time.setText(R.string.just_now);
                } else {
                    vh.time.setText(Utils.getTimeShowText(new Date(time), yesterday, today, year));
                    vh.time.setVisibility(View.VISIBLE);
                }
            }
            vh.content.setText(msg.content);
            return view;
        }

        private boolean displayTime(int position) {
            if (position == 0) {
                return true;
            } else {
                long time1 = getItem(position - 1).create_time;
                long time2 = getItemId(position);
                return Math.abs(time2 - time1) > DEFAULT_TIME_SPAN;
            }

        }
    }


    static class ViewHolder {
        @InjectView(R.id.avatar)
        RoundedImageView avatar;

        @InjectView(R.id.time)
        TextView time;

        @InjectView(R.id.content)
        TextView content;

        ViewHolder(View view) {
            ButterKnife.inject(this, view);
        }
    }
}
